package com.lxg.ai.config;

import com.lxg.ai.handler.InvoiceHandler;
import com.lxg.ai.listener.MyChatListener;
import com.lxg.ai.properties.DeepSeekProperties;
import com.lxg.ai.service.*;
import dev.langchain4j.agent.tool.graalvm.GraalVmJavaScriptExecutionTool;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.web.search.WebSearchTool;
import dev.langchain4j.web.search.searchapi.SearchApiWebSearchEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.time.Duration;
import java.util.List;

@Configuration
public class ChatLanguageModelConfig {

    @Autowired
    private DeepSeekProperties deepSeekProperties;


    @Bean
    public ChatLanguageModel chatLanguageModel() {
        ChatLanguageModel chatModel = OpenAiChatModel.builder()
                .logRequests(true)    // 启用请求日志
                .logResponses(true)   // 启用响应日志
                .maxRetries(0)  // 设置重试策略
                .timeout(Duration.ofSeconds(600000)) // 设置10秒超时
                .listeners(List.of(new MyChatListener()))
                .apiKey(deepSeekProperties.getApiKey())
                .modelName(deepSeekProperties.getModel())
                .baseUrl(deepSeekProperties.getBaseUrl()).build();
        return chatModel;
    }

    @Bean
    public ChatAssistant chatAssistant() {
        return AiServices.builder(ChatAssistant.class)
                .chatLanguageModel(chatLanguageModel())
                .build();
    }


    @Bean
    public SentimentAnalyzer sentimentAssistant() {
        return AiServices.builder(SentimentAnalyzer.class)
                .chatLanguageModel(chatLanguageModel())
                .build();
    }


    @Bean
    public StreamingChatLanguageModel streamingChatLanguageModel() {
        return OpenAiStreamingChatModel.builder()
                .logRequests(true)    // 启用请求日志
                .logResponses(true)   // 启用响应日志
                .timeout(Duration.ofSeconds(60)) // 设置10秒超时
                .listeners(List.of(new MyChatListener()))
                .apiKey(deepSeekProperties.getApiKey())
                .modelName(deepSeekProperties.getModel())
                .baseUrl(deepSeekProperties.getBaseUrl()).build();
    }

    @Bean
    public StreamChatAssistant streamChatAssistant() {
        // 业务逻辑 ToolExecutor
//        ToolExecutor toolExecutor = (toolExecutionRequest, memoryId) -> {
//            String arguments1 = toolExecutionRequest.arguments();
//            System.out.println("arguments1 =>>>> " + arguments1);
//            return "开具成功";动态工具配置
//LangChain4j 支持动态工具配置，开发者可以基于用户输入的上下文，在运行时动态加载工具。通过 ToolProvider 接口，工具集会在每次请求时动态生成。
//例如，只有当用户提到 “booking” 时才加载相关的工具：
//        };
        return AiServices.builder(StreamChatAssistant.class)
                .streamingChatLanguageModel(streamingChatLanguageModel())
//                .toolProvider((toolProviderRequest)->{
//                    if (toolProviderRequest.userMessage().singleText().contains("booking")) {
//                        ToolSpecification toolSpecification = ToolSpecification.builder()
//                                .name("get_booking_details")
//                                .description("Returns booking details")
//                                .parameters(JsonObjectSchema
//                                        .builder()
//                                        .addStringProperty("companyName", "公司名称")
//                                        .addStringProperty("dutyNumber", "税号")
//                                        .addNumberProperty("amount", "金额")
//                                        .build())
//                                .build();
//                        return ToolProviderResult.builder()
//                                .add(toolSpecification, toolExecutor)
//                                .build();
//                    } else {
//                        return null;
//                    }
//                })
                .chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(20))//取最新的10条做上下文//如需自定义持久化方式,可以实现ChatMemoryStore接口:
                .build();
    }

//    /**
//     * 编码注入函数
//     * @param chatLanguageModel
//     * @return
//     */
//    @Bean
//    public FunctionAssistant functionAssistant(ChatLanguageModel chatLanguageModel) {
//        // 工具说明 ToolSpecification
//        ToolSpecification toolSpecification = ToolSpecification.builder()
//                .name("invoice_assistant")
//                .description("根据用户提交的开票信息，开具发票")
//                .parameters(JsonObjectSchema
//                        .builder()
//                        .addStringProperty("companyName", "公司名称")
//                        .addStringProperty("dutyNumber","税号")
//                        .addNumberProperty("amount","金额")
//                        .build())
//                .build();
//
//        // 业务逻辑 ToolExecutor
//        ToolExecutor toolExecutor = (toolExecutionRequest, memoryId) -> {
//            String arguments1 = toolExecutionRequest.arguments();
//            System.out.println("arguments1 =>>>> " + arguments1);
//            return "开具成功";
//        };
//
//        return AiServices.builder(FunctionAssistant.class)
//                .chatLanguageModel(chatLanguageModel)
//                .tools(Map.of(toolSpecification, toolExecutor))
//                .build();
//    }

    /**
     * 注解注入
     *
     * @param chatLanguageModel
     * @return
     */
    @Bean
    public FunctionAssistant functionAssistant(ChatLanguageModel chatLanguageModel) {
        return AiServices.builder(FunctionAssistant.class)
                .chatLanguageModel(chatLanguageModel)
                .tools(new InvoiceHandler())
                .build();
    }


    @Bean
    public DynamicFunctionAssistant dynamicFunctionAssistant(ChatLanguageModel chatLanguageModel) {
        return AiServices.builder(DynamicFunctionAssistant.class)
                .chatLanguageModel(chatLanguageModel)
                .tools(new GraalVmJavaScriptExecutionTool())
                .build();
    }

    @Bean
    public SearchChatAssistant searchChatAssistant(ChatLanguageModel chatLanguageModel) {
        SearchApiWebSearchEngine searchEngine = SearchApiWebSearchEngine.builder()
                .apiKey("p8SZVNAweqTtoZBBTVnXttcj")// 测试使用
                .engine("baidu")
                .build();

        WebSearchTool webSearchTool = WebSearchTool.from(searchEngine);
        return AiServices.builder(SearchChatAssistant.class).chatLanguageModel(chatLanguageModel).tools(webSearchTool).build();
    }

}
